package com.yichen.codesandbox.docker;

import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.ListContainersCmd;
import com.github.dockerjava.api.model.Container;
import com.github.dockerjava.core.DockerClientBuilder;

import java.util.List;

/**
 * @Author: yichenwu
 * @Date:2024/6/27 1:11
 */

/**
 * java 操作 Docker常用命令示例
 *
 */
public class DockerDemo {
    public static void main(String[] args) {
        // 获取dockerClient
        DockerClientBuilder dockerInstance = DockerClientBuilder.getInstance();
        DockerClient dockerClient = dockerInstance.build();
//        dockerClient.buildImageCmd();
        // 1. ping
//        PingCmd pingCmd = dockerClient.pingCmd();
//        pingCmd.exec();

        // 2. 拉取镜像：
        String image = "nginx:latest";
//        PullImageCmd pullImageCmd = dockerClient.pullImageCmd(image);
//        PullImageResultCallback pullImageResultCallback = new PullImageResultCallback(){
//            @Override
//            public void onNext(PullResponseItem item) {
//                System.out.println("开始下载镜像..." + item.getStatus());
//                super.onNext(item);
//            }
//        };
//        pullImageCmd.exec(pullImageResultCallback)
//                .awaitCompletion();
//        System.out.println("download succeed!");

        // 3. 创建容器：
//        CreateContainerCmd containerCmd = dockerClient.createContainerCmd(image);
//        CreateContainerResponse echo = containerCmd.withCmd("echo", "hello docker!").exec();
//        System.out.println(echo);

        // 4. 查看所有容器状态：
        ListContainersCmd listContainersCmd = dockerClient.listContainersCmd();
        List<Container> exec = listContainersCmd.withShowAll(true).exec();
        for (Container container :exec) {
            System.out.println(container);
        }

        // 5. 启动容器
//        String containerId = "sha256:e0c9858e10ed8be697dc2809db78c57357ffc82de88c69a3dee5d148354679ef";
//        dockerClient.startContainerCmd(containerId).exec();

        // 6. 查看日志：
//        LogContainerResultCallback logContainerResultCallback = new LogContainerResultCallback() {
//            @Override
//            public void onNext(Frame item) {
//                System.out.println(item.getStreamType());
//                System.out.println("日志：" + new String(item.getPayload()));
//                super.onNext(item);
//            }
//        };
//// 阻塞等待日志输出
//        dockerClient.logContainerCmd(containerId)
//                .withStdErr(true)
//                .withStdOut(true)
//                .exec(logContainerResultCallback)
//                .awaitCompletion();

        // 7. 删除容器：
//        dockerClient.removeContainerCmd(containerId).withForce(true).exec();

        // 8. 删除镜像：
        // dockerClient.removeImageCmd(image).exec();
    }
}
